import React, { useContext, useRef } from "react";
import classNames from "classnames";
import { useDndMonitor, useDraggable } from "@dnd-kit/core";
import { DeleteOutlined, DragOutlined } from "@ant-design/icons";
import FunFormCtx, { FunFormElement } from "../../core";
import { WidgetRender } from "../../widgets";
import { useHover } from "ahooks";
import styles from "../index.module.less";

const DragItem = (props: {
  widget: FunFormWidget;
  colId?: string;
  labelWidth: number;
  isOverLay?: boolean;
  mode: "horizontal" | "vertical";
  onSelect?(): void;
  onDelete?(): void;
}) => {
  const { setActivedWidget, activedElement, setActivedElement } = useContext(
    FunFormCtx
  );

  const { setNodeRef, attributes, listeners, isDragging } = useDraggable({
    id: props.widget.uuid,
    data: {
      name: FunFormElement.Widget,
      value: props.widget,
      colId: props.colId,
    },
  });
  const ref = useRef(null);

  const isHovering = useHover(ref);

  useDndMonitor({
    onDragStart({ active }) {
      const current = active.data.current as {
        name: FunFormElement;
        value: FunFormWidget;
      };
      if (current && current.name === FunFormElement.Widget) {
        setActivedWidget(current.value);
      } else {
        setActivedWidget(undefined);
      }
    },
  });

  if (props.isOverLay) {
    return (
      <div
        className={classNames(
          styles.blockDrop,
          styles.hideBorder,
          props.isOverLay && styles.dragging
        )}
      >
        <WidgetRender
          {...(props.widget as FunFormWidget)}
          labelWidth={props.labelWidth}
          mode="horizontal"
        ></WidgetRender>
      </div>
    );
  }

  return (
    <div
      ref={ref}
      className={classNames(styles.blockDrop, styles.hideBorder, {
        [styles.actived]: activedElement?.element.uuid === props.widget?.uuid,
        [styles.isDragging]: isDragging,
        [styles.isHovering]: isHovering,
      })}
      style={{ cursor: "pointer" }}
      onClick={props.onSelect}
    >
      <WidgetRender
        {...(props.widget as FunFormWidget)}
        labelWidth={props.labelWidth}
        mode={props.mode}
      ></WidgetRender>

      {isHovering && (
        <div className={styles.tools}>
          <DeleteOutlined
            title="删除"
            onClick={(e) => {
              e.stopPropagation();
              if (activedElement?.element.uuid === props.widget?.uuid) {
                setActivedElement(undefined);
              }
              props.onDelete && props.onDelete();
            }}
          />
        </div>
      )}
      {isHovering && (
        <div
          className={styles.dragHandle}
          ref={setNodeRef}
          {...attributes}
          {...listeners}
        >
          <DragOutlined title="移动" />
        </div>
      )}
    </div>
  );
};

export default DragItem;
